<template>
    <div id="uploadIndex">
        <el-upload
          :disabled="auditFlag"
          ref="uploadRef"
          :file-list="fileList"
          action="#"
          list-type="picture-card"
          :http-request="requestUpload"
          :before-upload="beforeUpload">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url" alt=""
            >
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <i class="el-icon-download"></i>
              </span>
              <span
                v-if="!disabled && ! auditFlag"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
    import { listFiles, getFiles, delFiles, addStudentFileUpload, updateFiles } from "@/api/bmxt/files";
    const KB = 1024;
    export default {
        name: "uploadIndex",
        // 接收父组件向子组件的传值
        props:{
            fatherValue: { type : Object },
            // 文件大小限制
            addStudentFlag:{
                type: Boolean,
                require: false,
                default: false
            },
            auditFlag:{
                type: Boolean,
                require: false,
                default: false
            },
            limitSize:{
                type: Number,
                require: false,
                default: 2
            },
            filePathArray:{
                type: Array,
                require: false,
                default: ()=>[]
            },
            // 类型限制  默认是图片
            limitType:{
                type: String,
                require: false,
                default: 'image/jpeg'
            },
            // 数量限制  默认是1
            limitNumber:{
                type: Number,
                require: false,
                default: 1
            },
            // 文件材料的类型   文件类型 1-证件照 2-身份证正面 3-身份证反面 4-毕业证 5-证明材料
            sourcesType:{
                type: Number,
                require: false,
                default: 1
            },
            // 错误信息
            errMsg:{
                type: String,
                require: false,
                default: '文件格式错误，请上传JPG类型的图片。'
            },
            /*fileList:{
                type: Array,
                require: false,
                default: ()=>[]
            }*/
        },
        data(){
            return {
              uploadFileList: [],
              fileList: [],
              options: {
                  uploadImg: undefined
              },
              dialogImageUrl: '',
              dialogVisible: false,
              disabled: false,
            }
        },
        methods:{
          attachUploadSuccess(response, file, fileList) {
            console.log("文件上传成功")
            console.log(response)
            console.log(file)
            if (response.code == 200) {
              this.fileList.push({
                uid: response.data.id,
                name: response.data.fileName,
                url: response.data.url,
              })
            } else {
              this.$message.error(response.message)
            }
          },
          // 覆盖默认的上传行为
          requestUpload(param){
            // 学生添加时  图片存储到本地
            if(this.addStudentFlag){  //URL.createObjectURL(file.raw)  url: URL.createObjectURL(param.file.raw)
              const reader = new FileReader();
              reader.readAsDataURL(param.file);
              reader.onload = () => {
                this.fileList.push({
                  uid: param.file.uid,
                  name: param.file.uid+".jpg",
                  url: reader.result
                })
                // 添加到上传列表中 返回到父组件
                this.uploadFileList.push(param.file)
                this.$emit('event', this.uploadFileList,this.sourcesType)
              };
              return ;
            }
            let formData = new FormData();
            formData.append("studentId",this.fatherValue.studentId);
            formData.append("fileTypeId",this.sourcesType.toString());
            formData.append("files",param.file);
            addStudentFileUpload(formData).then(resp=>{
              if(resp.code == 200){
                let item = resp.data;
                let x = item.filePath.lastIndexOf("\/")
                let y = item.filePath.lastIndexOf("\.")
                let uid = item.filePath.substring(x+1,y);
                this.fileList.push({
                  fileId: item.fileId,
                  uid: param.file.uid,
                  name: uid+".jpg",
                  url: process.env.VUE_APP_BASE_API + item.filePath,
                })

                this.$modal.msgSuccess("上传成功");
              }
            })
          },
          handleRemove(file) {
            this.$modal.confirm('是否确认删除该文件？').then(()=> {
              let item = this.fileList.find((item)=>item.uid == file.uid)
              // 处理文件添加业务
              if(this.addStudentFlag){
                this.fileList = this.fileList.filter((item)=>item.uid != file.uid)
                this.uploadFileList = this.uploadFileList.filter((item)=>item.uid != file.uid)
                this.$emit('event', this.uploadFileList,this.sourcesType)
                return ;
              }

              delFiles(Number(file.fileId)).then(resp=>{
                if(resp.code == 200){
                  this.fileList = this.fileList.filter((item)=>item.uid != file.uid)
                  this.$modal.msgSuccess("删除成功");
                }
              })
            }).then(() => {
            }).catch(() => {});

          },
          handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
          },
          handleDownload(file) {
            let a = document.createElement('a')
            a.href = file.url
            a.download = file.name
            a.click()
          },
          // 上传预处理
          beforeUpload(file){
              let isLt2M = file.size / 1024 / 1024 < this.limitSize;
              if (!isLt2M) {
                 this.msgError("上传图片或视频大小不能超过"+this.limitSize+"MB!")
                 return false;
              }
              // 验证是否是图片
              if (file.type.indexOf(this.limitType) == -1) {
                this.msgError(this.errMsg)
                  return false;
              } else if (this.fileList.length >= this.limitNumber){ // 文件个数
                 this.$modal.msgError("最多只能上传"+this.limitNumber+"个文件！");
                 return false;
              }else {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => {
                  this.options.uploadImg = reader.result;
                };
                return true;
              }

              /*if(fileSize > 100*KB){
                Toast('大小超过100KB');
                return false;
              }
              if(fileSize < 30*KB){
                Toast('不能小于30KB');
                return false;
              }*/
          },
          /*// 覆盖默认的上传行为
          requestUpload(param){
              console.log("子组件上传文件完成回传数据");
              console.log(param.file);
              // 返回给父组件  uploadComplete自定义事件
              this.$emit('uploadComplete',param.file)
          },*/
        },
        created() {
          this.fileList = []
          if(this.filePathArray != null && this.filePathArray.length>0){
            this.filePathArray.forEach(item=>{
              let x = item.filePath.lastIndexOf("\/")
              let y = item.filePath.lastIndexOf("\.")
              let uid = item.filePath.substring(x+1,y);
              this.fileList.push({
                fileId: item.fileId,
                uid: uid,
                name: uid+".jpg",
                url: process.env.VUE_APP_BASE_API + item.filePath,
              })
            })
          }
        }
    }
</script>

<style scoped>
  /*::v-deep .el-upload--picture-card {
    display: none !important; !* 上传按钮隐藏 *!
  }*/
</style>
